package com.taiyi.renaissancemall.ui.main.first.memberBenefits.editOrder;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.taiyi.renaissancemall.R;
import com.taiyi.renaissancemall.Utils.PayResult;
import com.taiyi.renaissancemall.Utils.ToastUtils;
import com.taiyi.renaissancemall.base.BaseActivity;
import com.taiyi.renaissancemall.base.MyApp;
import com.taiyi.renaissancemall.bean.AddressListBean;
import com.taiyi.renaissancemall.bean.FreightBean;
import com.taiyi.renaissancemall.bean.MemberEditOrderBean;
import com.taiyi.renaissancemall.bean.MemberOrderCommitBean;
import com.taiyi.renaissancemall.bean.PersonInfoBean;
import com.taiyi.renaissancemall.ui.main.first.memberBenefits.MemberBenefitsActivity;
import com.taiyi.renaissancemall.ui.main.paysuccess.PaySuccessActivity;
import com.taiyi.renaissancemall.ui.mine.address.ShippingAddressActivity;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.modelpay.PayReq;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

//会员福利商品填写订单购买
public class MemberEditOrderActivity extends BaseActivity<MemberEditOrderView, MemberEditOrderPresent> implements MemberEditOrderView {

    @BindView(R.id.backIv)
    ImageView backIv;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.rightIv)
    ImageView rightIv;
    @BindView(R.id.tv_member_user_name)
    TextView tvMemberUserName;
    @BindView(R.id.tv_member_user_type)
    TextView tvMemberUserType;
    @BindView(R.id.iv_member_user_edit)
    ImageView ivMemberUserEdit;
    @BindView(R.id.tv_member_user_phone)
    TextView tvMemberUserPhone;
    @BindView(R.id.tv_member_user_address)
    TextView tvMemberUserAddress;
    @BindView(R.id.iv_member_shop_icon)
    ImageView ivMemberShopIcon;
    @BindView(R.id.tv_member_shop_name)
    TextView tvMemberShopName;
    @BindView(R.id.tv_member_shop_price)
    TextView tvMemberShopPrice;
    @BindView(R.id.constraintLayout)
    LinearLayout constraintLayout;
    @BindView(R.id.textView19)
    TextView textView19;
    @BindView(R.id.textView20)
    TextView textView20;
    @BindView(R.id.textView25)
    TextView textView25;
    @BindView(R.id.iv_member_total_money)
    TextView ivMemberTotalMoney;
    @BindView(R.id.tv_member_freight)
    TextView tvMemberFreight;
    @BindView(R.id.tv_member_all_money)
    TextView tvMemberAllMoney;
    @BindView(R.id.tv_member_buy)
    TextView tvMemberBuy;
    @BindView(R.id.top)
    ConstraintLayout top;
    @BindView(R.id.selectShippingAddressTv)
    TextView selectShippingAddressTv;
    @BindView(R.id.ll_member_show_address)
    LinearLayout llMemberShowAddress;
    @BindView(R.id.paymentMethod)
    TextView paymentMethod;
    @BindView(R.id.aliPayTv)
    TextView aliPayTv;
    @BindView(R.id.weChatTv)
    TextView weChatTv;
    @BindView(R.id.balancePaymentTv)
    TextView balancePaymentTv;
    @BindView(R.id.availableBalanceTv)
    TextView availableBalanceTv;
    @BindView(R.id.orderRemarks)
    TextView orderRemarks;
    @BindView(R.id.orderRemarksContentEt)
    EditText orderRemarksContentEt;
    private String cId = "";
    private String sNum = "";
    private String addressId = "";
    private String payType = "";
    private int SDK_PAY_FLAG = 1001;
    private String order_id;
    private String stInfo;
    private PayReq payRequest;
    private String jcYunFei;
    private String dzYunFei;
    private String price;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_member_edit_order;
    }

    @Override
    public MemberEditOrderPresent initPresenter() {
        return new MemberEditOrderPresent();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        titleTv.setText(getString(R.string.fillOrder));
        cId = getIntent().getStringExtra("commodityid");
        sNum = getIntent().getStringExtra("salenum");
        showProgress();
        presenter.toEditDetail(cId, sNum);
        presenter.getUserDetail();
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(top).init();
    }

    @Override
    protected void initData() {
    }

    @Override
    public void initEvent() {

    }

    @OnClick({R.id.backIv, R.id.tv_member_buy, R.id.iv_member_user_edit, R.id.selectShippingAddressTv, R.id.aliPayTv, R.id.weChatTv, R.id.balancePaymentTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backIv:
                finish();
                break;
            case R.id.selectShippingAddressTv:
            case R.id.iv_member_user_edit:
                startActivity(new Intent(this, ShippingAddressActivity.class));
                break;
            case R.id.tv_member_buy:
                String remark = orderRemarksContentEt.getText().toString().trim();
                sNum = "1";
                if (TextUtils.isEmpty(addressId)) {
                    ToastUtils.showLongToast("请选择地址");
                    return;
                }
                if (TextUtils.isEmpty(payType)) {
                    ToastUtils.showLongToast("请选择支付类型");
                    return;
                }
                showProgress();
                presenter.toBuyNow(cId, payType, sNum, addressId, remark);
                break;
            case R.id.aliPayTv:
                payType = "2";
                aliPayTv.setSelected(true);
                weChatTv.setSelected(false);
                balancePaymentTv.setSelected(false);
                break;
            case R.id.weChatTv:
                payType = "1";
                weChatTv.setSelected(true);
                aliPayTv.setSelected(false);
                balancePaymentTv.setSelected(false);
                break;
            case R.id.balancePaymentTv:
                payType = "3";
                balancePaymentTv.setSelected(true);
                weChatTv.setSelected(false);
                aliPayTv.setSelected(false);
                break;
        }
    }

    @Override
    public void toEditSuccess(MemberEditOrderBean memberEditOrderBean) {
        hideProgress();
        if (memberEditOrderBean.addressParams != null
                && !"".equals(memberEditOrderBean.addressParams)) {
            llMemberShowAddress.setVisibility(View.VISIBLE);
            selectShippingAddressTv.setVisibility(View.GONE);
            tvMemberUserName.setVisibility(View.VISIBLE);
            if ("1".equals(memberEditOrderBean.addressParams.type)) {
                tvMemberUserType.setVisibility(View.VISIBLE);
            } else {
                tvMemberUserType.setVisibility(View.GONE);
            }
            tvMemberUserName.setText(memberEditOrderBean.addressParams.name);
            tvMemberUserPhone.setText(memberEditOrderBean.addressParams.tel);
            String member_province = "";
            String member_city = "";
            String member_area = "";
            String member_address = "";
            if (!TextUtils.isEmpty(memberEditOrderBean.addressParams.provincename)
                    && memberEditOrderBean.addressParams.provincename != null) {
                member_province = memberEditOrderBean.addressParams.provincename;
            }
            if (!TextUtils.isEmpty(memberEditOrderBean.addressParams.cityname)
                    && memberEditOrderBean.addressParams.cityname != null) {
                member_city = memberEditOrderBean.addressParams.cityname;
            }
            if (!TextUtils.isEmpty(memberEditOrderBean.addressParams.areaName)
                    && memberEditOrderBean.addressParams.areaName != null) {
                member_area = memberEditOrderBean.addressParams.areaName;
            }
            if (!TextUtils.isEmpty(memberEditOrderBean.addressParams.address)
                    && memberEditOrderBean.addressParams.address != null) {
                member_address = memberEditOrderBean.addressParams.address;
            }
            String address_member = member_province
                    + member_city
                    + member_area
                    + member_address;
            tvMemberUserAddress.setText(address_member);
            addressId = memberEditOrderBean.addressParams.useraddress_id + "";
            presenter.getFreight(addressId);
        } else {
            llMemberShowAddress.setVisibility(View.GONE);
            selectShippingAddressTv.setVisibility(View.VISIBLE);
            tvMemberUserName.setVisibility(View.GONE);
            tvMemberUserType.setVisibility(View.GONE);
        }

        Glide.with(MemberEditOrderActivity.this).load(memberEditOrderBean.product.smallimgurl).into(ivMemberShopIcon);
        tvMemberShopName.setText(memberEditOrderBean.product.name);
        tvMemberShopPrice.setText(memberEditOrderBean.product.price);
        ivMemberTotalMoney.setText(memberEditOrderBean.product.price);
        jcYunFei = memberEditOrderBean.product.yunfei;
        price = memberEditOrderBean.product.price;
    }

    @Override
    public void toEditFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void toBuyNowSuccess(MemberOrderCommitBean memberOrderCommitBean) {
        hideProgress();
        stInfo = memberOrderCommitBean.aliparam;
        order_id = memberOrderCommitBean.orderid;
        if ("2".equals(payType)) {//支付宝支付
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(MemberEditOrderActivity.this);
                    Map<String, String> result = alipay.payV2(stInfo, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();

        } else if ("1".equals(payType)) {
            //微信支付
            //这里的appid，替换成自己的即可
            IWXAPI api = MyApp.getWxApi();
            api.registerApp(MyApp.getAppId());
            //这里的bean，是服务器返回的json生成的bean
            payRequest = new PayReq();
            payRequest.appId = memberOrderCommitBean.appid;
            payRequest.partnerId = memberOrderCommitBean.partnerid;
            payRequest.prepayId = memberOrderCommitBean.prepayid;
            payRequest.packageValue = "Sign=WXPay";//固定值
            payRequest.nonceStr = memberOrderCommitBean.noncestr;
            payRequest.timeStamp = memberOrderCommitBean.timestamp;
            payRequest.sign = memberOrderCommitBean.sign;

            //发起请求，调起微信前去支付
            api.sendReq(payRequest);
        } else if ("3".equals(payType)) {
            showProgress();
            presenter.findOrderState(order_id);
        }
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == SDK_PAY_FLAG) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String resultInfo = payResult.getResult();
                if ("9000".equals(payResult.getResultStatus())) {
                    showProgress();
                    presenter.findOrderState(order_id);
                }
            } else {
                ToastUtils.showLongToast("支付异常");
            }
        }


    };

    @Override
    public void toBuyNowFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void getUserDetailSuccess(PersonInfoBean personInfoBean) {
        hideProgress();
        availableBalanceTv.setText(personInfoBean.getLiquannumti());
    }

    @Override
    public void getUserDetailFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void getOrderStateSuccess() {
        hideProgress();
        Intent intent = new Intent(MemberEditOrderActivity.this, PaySuccessActivity.class);
        intent.putExtra("payWay", payType);
        intent.putExtra("payAmount", tvMemberAllMoney.getText().toString().trim());
        intent.putExtra("orderId", order_id);
        startActivity(intent);
        finish();
    }

    @Override
    public void getOrderStateFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void getFreightSuccess(FreightBean freightBean) {
        hideProgress();
        dzYunFei = freightBean.getSumyunfei();
        String yf = "";
        double zYunFei = Double.parseDouble(jcYunFei)
                + Double.parseDouble(dzYunFei);
        String zYunFeiFormat = new DecimalFormat("0.00").format(zYunFei);
        tvMemberFreight.setText(zYunFeiFormat);

        double allMoney = Double.parseDouble(price) + zYunFei;
        String decimalFormat = new DecimalFormat("0.00").format(allMoney);
        tvMemberAllMoney.setText(decimalFormat);

    }

    @Override
    public void getFreightFailure(String msg) {
        hideProgress();
    }

    @Subscribe
    public void getAddress(AddressListBean.AddresslistBean addresslistBean) {
        llMemberShowAddress.setVisibility(View.VISIBLE);
        selectShippingAddressTv.setVisibility(View.GONE);
        tvMemberUserName.setVisibility(View.VISIBLE);
        addressId = addresslistBean.getUseraddress_id();
        if ("1".equals(addresslistBean.getType())) {
            tvMemberUserType.setVisibility(View.VISIBLE);
        } else {
            tvMemberUserType.setVisibility(View.GONE);
        }
        String event_province = "";
        String event_city = "";
        String event_area = "";
        String event_address = "";
        if (!TextUtils.isEmpty(addresslistBean.getProvincename())
                && addresslistBean.getProvincename() != null) {
            event_province = addresslistBean.getProvincename();
        }
        if (!TextUtils.isEmpty(addresslistBean.getCityname())
                && addresslistBean.getCityname() != null) {
            event_city = addresslistBean.getCityname();
        }
        if (!TextUtils.isEmpty(addresslistBean.getAreaname())
                && addresslistBean.getAreaname() != null) {
            event_area = addresslistBean.getAreaname();
        }
        if (!TextUtils.isEmpty(addresslistBean.getAddress())
                && addresslistBean.getAddress() != null) {
            event_address = addresslistBean.getAddress();
        }
        String address_member = event_province
                + event_city
                + event_area
                + event_address;
        if ("1".equals(addresslistBean.getType())) {
            tvMemberUserType.setVisibility(View.VISIBLE);
        } else {
            tvMemberUserType.setVisibility(View.GONE);
        }
        tvMemberUserName.setText(addresslistBean.getName());
        tvMemberUserPhone.setText(addresslistBean.getTel());
        tvMemberUserAddress.setText(address_member);
        showProgress();
        presenter.getFreight(addressId);
    }


    @Subscribe
    public void paySuccess(String s) {
        if (s.startsWith("paySuccess")) {
            showProgress();
            presenter.findOrderState(order_id);
        }
    }

}
